<?php
if(isset($_SESSION['user_logged_in'])) {
	function lobby() {
		global $main;
		$response=new xajaxResponse();
		$id = $main->query_first('SELECT id, player_1, player_2 FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if(!empty($id)) {
			$data = '<div class="lobby_header">Mäng '.$id['id'].'</div>';
			$data .= '<div class="lobby_leave" onclick="xajax_leave_game();">Lahku mängust</div>';
			$data .= '<div class="lobby_header">Osalejad</div>';
			if($id['player_1'] != 0) {
				$player = $main->query_first("SELECT facebook_name, facebook_id, activity FROM bs_users WHERE id = " .$id['player_1']);
				$data .= '<div class="lobby_item rollover" onclick="openWindow('."'https://www.facebook.com/profile.php?id=".$player['facebook_id']."', '_blank'".');">'.utf8_encode($player['facebook_name']);
				if(strtotime('now-5minutes') > strtotime($player['activity'])) {
					$time=$main->getAwayTime(strtotime($player['activity']));
					$data .= '<br /> Eemal: <b>' . $time . '</b>';
				}
				$data .= '</div>';
			}
			if($id['player_2'] != 0) {
				$player = $main->query_first("SELECT facebook_name, facebook_id, activity FROM bs_users WHERE id = " .$id['player_2']);
				$data .= '<div class="lobby_item rollover" onclick="openWindow('."'https://www.facebook.com/profile.php?id=".$player['facebook_id']."', '_blank'".');">'.utf8_encode($player['facebook_name']);
				if(strtotime('now-5minutes') > strtotime($player['activity'])) {
					$time=$main->getAwayTime(strtotime($player['activity']));
					$data .= '<br /> (eemal <b>' . $time . '</b>)';
				}
				$data .= '</div>';
			}
		}else {
			$list = $main->query('SELECT id, player_1, player_2, finished, winner FROM bs_games ORDER BY time DESC LIMIT 100');
			$data = '<div class="lobby_header">Käimasolevad mängud</div>';
			while($output=&$main->fetch_array($list)) {
				if(($output['player_1'] == 0 || $output['player_2'] == 0) && $output['finished'] == 0) {
					if($output['player_1'] == 0 && $output['player_2'] == 0) {
						$players = 0;	
					}else {
						$players = 1;	
					}
					$data .= '<div class="lobby_item open" onclick="xajax_join_game('.$output['id'].');">Mäng '.$output['id'].' ['.$players.'/2]</div>';
				}else {
					if($output['finished'] == 0) {
						$data .= '<div class="lobby_item closed">Mäng '.$output['id'].' [täis]</div>';	
					}else{
						$data .= '<div class="lobby_item closed">Mäng '.$output['id'].' [läbi]</div>';	
					}
				}
			}
			$data .= '<div class="lobby_item rollover" onclick="xajax_new_game();">Alusta uut mäng</div>';
		}
		$response->assign("lobby", "innerHTML", $data);
 		return $response;
	}
	$xajax->registerFunction('lobby');
	function new_game() {
		global $main;
		$response=new xajaxResponse();
		$games = $main->query_first('SELECT COUNT(id) as total FROM bs_games WHERE creator = "' . $_SESSION['user_logged_in'] . '" AND finished = "0"');
		if($games['total'] < 3) {
			$insert['player_1'] = $_SESSION['user_logged_in'];
			$insert['creator'] = $_SESSION['user_logged_in'];
			$main->query_insert("games", $insert);
			$response->script('xajax_game();');
		}else {
			$response->assign("popup", "style.display", 'block');
			$response->assign("popup_message", "innerHTML", 'Liiga palju lõpetamata mänge!');
		}
 		return $response;
	}
	$xajax->registerFunction('new_game');
	function game() {
		global $main;
		$response=new xajaxResponse();
		$playing = $main->query_first('SELECT id FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if(!empty($playing)) {
			$battle = $main->query_first('SELECT * FROM bs_battletables WHERE game_id = "'.$playing['id'].'" LIMIT 1');
			if(empty($battle) || ($battle['player_2'] != $_SESSION['user_logged_in'] && empty($battle['player_1_data'])) || ($battle['player_1'] != $_SESSION['user_logged_in'] && empty($battle['player_2_data']))) {
				$ships = array(1,1,1,1,2,2,2,3,3,4);
				for($i = 0;$i<count($ships);$i++) {
					$data .= '<div class="ship ship'.$ships[$i].'" onclick="activateShip('.$ships[$i].', this);">'.$ships[$i].'x</div>';
				}
				$data .= '<div class="clear"></div>';
				$response->assign("ships", "innerHTML", $data);
				$data = "";
				for($i = 0;$i<10; $i++) {
					for($j = 0;$j<10; $j++) {
						$data .= '<div id="grid'.$j.$i.'" class="grid_item" onclick="gridClick('.$j.','.$i.');" onmouseover="gridOver('.$j.','.$i.')"; onmouseout="gridOut('.$j.','.$i.');"></div>';
					}
					$data .= '<div class="clear"></div>';
				}
				$response->assign("gametable", "innerHTML", $data);
				$response->assign("game_buttons", "style.display", 'block');
			} else {
				if($battle['player_1'] == $_SESSION['user_logged_in']) {
					$data = $battle['player_1_data'];
				}else if($battle['player_2'] == $_SESSION['user_logged_in']) {
					$data = $battle['player_2_data'];
				}
				$table = explode(";",$data);
				$data = "";
				$num = 0;
				for($i = 0;$i<10; $i++) {
					for($j = 0;$j<10; $j++) {
						$current = explode(",",$table[$num++]);
						if($current[2] != 0) {
							$data .= '<div id="grid'.$j.$i.'" class="shipActive"></div>';
						}else {
							$data .= '<div id="grid'.$j.$i.'" class="grid_item"></div>';
						}
					}
					$data .= '<div class="clear"></div>';
				}
				$response->assign("gametable", "innerHTML", $data);
				$response->assign("ships", "innerHTML", '');
				$response->assign("game_buttons", "style.display", 'none');
			}
			$data = "";
			for($i = 0;$i<10; $i++) {
				for($j = 0;$j<10; $j++) {
					$data .= '<div id="gridopponent'.$j.$i.'" class="grid_item" onclick="gridClick('.$j.','.$i.');"></div>';
				}
				$data .= '<div class="clear"></div>';
			}
			$response->assign("info_header", "style.display", "none");
			$response->assign("gametable_opponent", "innerHTML", $data);
			$response->assign("game_info", "style.display", 'none');
			$response->script('xajax_lobby();startGame();');
		}
 		return $response;
	}
	$xajax->registerFunction('game');
	function updateGame() {
		global $main;
		$response=new xajaxResponse();
		$response->assign("info_header", "style.display", "block");
		$playing = $main->query_first('SELECT id, player_1, player_2 FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if(!empty($playing)) {
			$battle = $main->query_first('SELECT player_1_data, player_2_data FROM bs_battletables WHERE game_id = "'.$playing['id'].'" LIMIT 1');
			if(($playing['player_1'] != $_SESSION['user_logged_in'] && empty($battle['player_1_data'])) || ($playing['player_2'] != $_SESSION['user_logged_in'] && empty($battle['player_2_data']))) {
				$response->assign("info_header", "innerHTML", "Vastane paigutab laevu!");
				$response->assign("info_header", "className", "red");
			}else if(($playing['player_1'] != $_SESSION['user_logged_in'] && !empty($battle['player_1_data']) && empty($battle['player_2_data'])) || ($playing['player_2'] != $_SESSION['user_logged_in'] && !empty($battle['player_2_data']) && empty($battle['player_1_data']))) {
				$response->assign("info_header", "innerHTML", "Vastane ootab sinu taga!");
				$response->assign("info_header", "className", "red");
			}else {
				$response = checkTurns();
			}
		}
 		return $response;
	}
	function checkTurns($response) {
 		return $response;		
	}
	$xajax->registerFunction('updateGame');
	function battleship($arr) {
		global $main;
		$response=new xajaxResponse();
		$playing = $main->query_first('SELECT id FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if(!empty($playing)) {
			$str = "";
			for($i = 0;$i<count($arr);$i++) {
				$str .= implode(",",$arr[$i]) . ";";
			}
			$id = $main->query_first('SELECT id, player_1, player_2 FROM bs_battletables WHERE game_id = "'.$playing['id'].'" LIMIT 1');
			if(empty($id)) {
				$insert['game_id'] = $playing['id'];
				$insert['player_1'] = $_SESSION['user_logged_in'];
				$insert['player_1_data'] = $str;
				$main->query_insert("battletables",$insert);
			}else {
				if(empty($id['player_2']) && $id['player_1'] != $_SESSION['user_logged_in']) {
					$insert['game_id'] = $playing['id'];
					$insert['player_2'] = $_SESSION['user_logged_in'];
					$insert['player_2_data'] = $str;
					$main->query_insert("battletables",$insert);
				}
			}
		}
		$response->script('xajax_game();');
 		return $response;
	}
	$xajax->registerFunction('battleship');
	function join_game($id) {
		global $main;
		$response=new xajaxResponse();
		$data = $main->query_first('SELECT player_1, player_2, finished FROM bs_games WHERE id = ' . intval($id));
		$playing = $main->query_first('SELECT id FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if($data['finished'] == 0 && empty($playing)) {
			if($data['player_1'] == 0) {
				$update['player_1'] = $_SESSION['user_logged_in'];
			}else if($$data['player_2'] == 0) {
				$update['player_2'] = $_SESSION['user_logged_in'];
			}
			if(!empty($update)) {
				$main->query_update("games", $update, "id = '" . intval($id) . "'");
				$response->script('xajax_game();');
			}
		}
 		return $response;
	}
	$xajax->registerFunction('join_game');
	function leave_game() {
		global $main;
		$response=new xajaxResponse();
		$playing = $main->query_first('SELECT id FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if(!empty($playing)) {
			$data = $main->query_first('SELECT player_1, player_2, finished FROM bs_games WHERE id = ' . $playing['id']);
			if($data['player_1'] == $_SESSION['user_logged_in']) {
				$update['player_1'] = 0;
			}
			if($data['player_2'] == $_SESSION['user_logged_in']) {
				$update['player_2'] = 0;
			}
			if(!empty($update)) {
				$main->query_update("games", $update, "id = '" . $playing['id'] . "'");
				$response->script('xajax_lobby();');
			}
		}
		$response->assign("game_info", "style.display", 'block');
		$response->assign("game_table", "style.display", 'none');
 		return $response;
	}
	$xajax->registerFunction('leave_game');
	function init() {
		global $main;
		$response=new xajaxResponse();
		$id = $main->query_first('SELECT id, player_1, player_2 FROM bs_games WHERE (player_1 = "' . $_SESSION['user_logged_in'] . '" OR player_2 = "' . $_SESSION['user_logged_in'] . '") AND finished = "0" LIMIT 1');
		if(!empty($id)) {
			$response->script('xajax_game();');
		}else {
			$response->assign("game_info", "style.display", 'block');
			$response->assign("game_table", "style.display", 'none');
		}
		$response->script('xajax_lobby();');
 		return $response;
	}
	$xajax->registerFunction('init');
}
?>